//
//  PDFPagePickerGridViewController.m
//  Digital Seamonsters
//
//  Created by Adam Cue on 2/6/11.
//  Copyright Adam Cue 2011.
//
//  This program is licensed and distributed under the terms of the GNU General Public License.  
//	The text for the license can be found in the license.txt file in this project.
//

#import "PDFPagePickerGridViewController.h"
#import "AnnotationView.h"
#import "PDFPagePickerGridViewCell.h"

#define GRID_VIEW_CELL_SIZE          CGSizeMake(102, 136)
#define PAGE_DRAWING_FRAME           CGRectMake(0, 0, 96, 128)
#define GRID_VIEW_CELL_FRAME         CGRectMake(0, 0, 102, 136)

@implementation PDFPagePickerGridViewController

@synthesize images = _images;
@synthesize annotationViews = _annotationViews;
@synthesize delegate;

//Initialize with a PDF document.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil document:(CGPDFDocumentRef)selectedDocument annotationViews:(NSMutableArray *)annotations{
  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  if (self) {
    _images = [[NSMutableDictionary alloc] init];
    pdfDocument = CGPDFDocumentRetain(selectedDocument);
    self.annotationViews = annotations;
  }
  return self;
}
- (void)viewDidLoad {
  [super viewDidLoad];
	self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
}

- (void)dealloc {
	CGPDFDocumentRelease(pdfDocument);
	self.images = nil;
  self.annotationViews = nil;
  self.delegate = nil;
  
  [super dealloc];
}

#pragma GettersAndSetters
- (void)setPdfDocument:(CGPDFDocumentRef)selectedDocument{
  CGPDFDocumentRelease(pdfDocument);
	pdfDocument = CGPDFDocumentRetain(selectedDocument);
}

- (CGPDFDocumentRef)getPdfDocument{
  return pdfDocument;
}

#pragma mark AQGridViewDataSource
- (NSUInteger) numberOfItemsInGridView: (AQGridView *) gridView
{
	return CGPDFDocumentGetNumberOfPages(pdfDocument);
}

- (AQGridViewCell *) gridView: (AQGridView *) gridView cellForItemAtIndex: (NSUInteger) index
{
	static NSString * PDFPageCellIdentifier = @"PDFPageCellIdentifier";
	
	PDFPagePickerGridViewCell *cell = (PDFPagePickerGridViewCell *)[self.gridView dequeueReusableCellWithIdentifier:PDFPageCellIdentifier];
	if(cell == nil){ 
    cell = [[[PDFPagePickerGridViewCell alloc] initWithFrame:GRID_VIEW_CELL_FRAME 
                                             reuseIdentifier:PDFPageCellIdentifier 
                                         superViewController:self] autorelease];
  }
	if([self.images objectForKey:[NSString stringWithFormat:@"page%d", index]] == nil){
    [PDFPagePickerGridViewCell fillCell:cell 
                      forAnnotationView:[self.annotationViews objectAtIndex:index] 
                                andPage:[self loadPdfImageAtIndex:index] 
                               andCount:index+1];
	}
	else{
    [PDFPagePickerGridViewCell fillCell:cell 
                      forAnnotationView:[self.annotationViews objectAtIndex:index] 
                                andPage:[self.images objectForKey:[NSString stringWithFormat:@"page%d", index]] 
                               andCount:index+1];
	}														  
	return cell;
}

//Draw the certain page of the PDF.
- (UIImage *)loadPdfImageAtIndex:(NSInteger)index{
	UIGraphicsBeginImageContext(PAGE_DRAWING_FRAME.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(context, 0, PAGE_DRAWING_FRAME.size.height);
	CGContextScaleCTM(context, 1.0, -1.0);
	CGPDFPageRef page = CGPDFDocumentGetPage (pdfDocument, index + 1);
	CGContextConcatCTM(context, 
					   CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, PAGE_DRAWING_FRAME, 0, true));
  CGContextDrawPDFPage(context, page);
	UIImage * pdfImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	[self.images setObject:pdfImage forKey:[NSString stringWithFormat:@"page%d", index]];
	return pdfImage;
}

- (CGSize) portraitGridCellSizeForGridView: (AQGridView *) gridView{
	return GRID_VIEW_CELL_SIZE;
}

#pragma mark AQGridView Delegate
- (void) gridView: (AQGridView *) gridView didSelectItemAtIndex: (NSUInteger) index {
	[delegate pageSelected:index];
}

#pragma mark PDFPagePreviewViewDelegate
- (void)selected:(int)index{
	[delegate pageSelected:index];
}


@end
